# coding : utf-8
# @Author : 赐恩明
# vx : 17341788306

import os
import time
import cv2
from PIL import ImageGrab
from pymouse import PyMouse
from boss_robot.common.main import Run


class Tool:
    mouse = PyMouse()

    def __init__(self):
        self.cfg = Run()
        self.px = float(self.cfg.px)

    def cv2_click(self, path):
        global small, big
        try:
            smalldir = path
            ImageGrab.grab().save(rf'.\image_b\img.png')
            for _ in range(4):
                if os.path.exists(r'.\image_b\img.png'):
                    small = cv2.imread(rf'{smalldir}')
                    big = cv2.imread(rf'.\image_b\img.png')
                    break
                else:
                    time.sleep(0.5)
        except Exception as e:
            print(e)
            return False
        r = cv2.matchTemplate(small, big, cv2.TM_CCOEFF_NORMED)
        if os.path.exists(r'./image_b/img.before.png'):
            os.remove(r'./image_b/img.before.png')
        os.rename(r'./image_b/img.png', r'./image_b/img.before.png')
        r1 = cv2.minMaxLoc(r)
        if r1[1] > 0.70:
            x, y = r1[-1]
            y1, x1, z1 = small.shape
            x2 = int(x + (x1 // 2))
            y2 = int(y + (y1 // 2))
            self.mouse.click(int(x2 // self.px), int(y2 // self.px))
            return True
        else:
            print("找不到相似度匹配的图像")
            return False
